package com.cjm.one.config;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.TextModerationRequest;
import com.aliyun.green20220302.models.TextModerationResponse;
import com.aliyun.green20220302.models.TextModerationResponseBody;
import com.aliyun.teautil.models.RuntimeOptions;
import com.cjm.one.common.exception.GlobalException;
import com.cjm.one.common.result.ResultCodeEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import com.aliyun.teaopenapi.models.Config;
@Component
@Slf4j
public class GreenService {
    @Resource
    private Client greenClient;
    @Resource
    private GreenPropertis greenPropertis;
    /**
     * @description: 文本审核
     * @author: cjm
     * @date: 2025/4/24 14:51
     * @param: [content]
     * @return: boolean
     **/
    public boolean  textModeration(String content) {
        System.out.println("GreenService: " + greenClient);
        // 创建RuntimeObject实例并设置运行参数。
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        //检测参数构造
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", content);

        if (serviceParameters.get("content") == null || serviceParameters.getString("content").trim().length() == 0) {
            throw  new GlobalException(ResultCodeEnum.COMMENT_CONTENT_EMPTY);
        }

        TextModerationRequest textModerationRequest = new TextModerationRequest();
        /*
        文本检测service：内容安全控制台文本增强版规则配置的serviceCode，示例：chat_detection
        */
        textModerationRequest.setService("comment_detection");
        textModerationRequest.setServiceParameters(serviceParameters.toJSONString());
        try {
            // 调用方法获取检测结果。
            TextModerationResponse response = greenClient.textModerationWithOptions(textModerationRequest, runtime);
            // 打印检测结果。
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    TextModerationResponseBody result = response.getBody();
                    System.out.println(JSON.toJSONString(result));
                    Integer code = result.getCode();
                    if (code != null && code == 200) {
                        TextModerationResponseBody.TextModerationResponseBodyData data = result.getData();
                        log.info("accountId = [" + data + "]");
                        System.out.println("labels = [" + data.getLabels() + "]");
                        System.out.println("reason = [" + data.getReason() + "]");
                        // 关键修改点：解析riskLevel并决策 -------------------
                        String reasonJsonStr = data.getReason();
                        if (reasonJsonStr == null || reasonJsonStr.isEmpty()) {
                            log.warn("内容安全检测结果｜无风险等级信息: {}", reasonJsonStr);
                            return true; // 没有风险等级，按需处理（例如默认拦截）
                        }
                        JSONObject reasonJson = JSON.parseObject(reasonJsonStr);
                        String riskLevel = reasonJson.getString("riskLevel"); // 从reason中提取风险等级

                        log.info("内容安全检测结果｜风险等级: {}｜原因: {}｜敏感词: {}",
                                riskLevel,
                                reasonJson.getString("riskTips"),
                                reasonJson.getString("riskWords"));
                        // 根据风险等级决定是否通过
                        if ("high".equalsIgnoreCase(riskLevel)) {
                            log.warn("高风险内容拦截: {}", content);
                            return false; // 高风险直接拦截
                        } else if ("medium".equalsIgnoreCase(riskLevel)) {
                            log.warn("中风险内容需人工复审: {}", content);
                            return false; // 中风险也拦截（按业务需求调整）
                        } else {
                            return true; // low/pass 放行
                        }


                    } else {
                        System.out.println("text moderation not success. code:" + code);
                        throw new GlobalException(ResultCodeEnum.COMMENT_DETECTION_FAIL);
                    }
                } else {
                    System.out.println("response not success. status:" + response.getStatusCode());
                    throw new GlobalException(ResultCodeEnum.COMMENT_DETECTION_ERROR);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
